﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cow.Module;
using System.IO;
using System.CodeDom;

namespace Cow.Handler
{
    /// <summary>
    /// 生成实体对象模型代码
    /// </summary>
    /// 
    public class ExportMapHandler : ExportFromCodeDom
    {
        public override string SuffixName
        {
            get { return "Map.cs"; }
        }

        protected override CodeNamespace CreateCode(Design design)
        {
            CodeNamespace codeNamespace = new CodeNamespace(design.NameSpace);
            // 添加命名空间
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Data.Entity.ModelConfiguration"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("Forest.Cat.Domain.Entities"));
            // 创建类
            CodeTypeDeclaration exportClass = new CodeTypeDeclaration(design.ModuleName + "Map");
            CodeTypeReference baseType = new CodeTypeReference("EntityTypeConfiguration");
            baseType.TypeArguments.Add(design.ModuleName);
            exportClass.IsPartial = true;
            exportClass.BaseTypes.Add(baseType);
            // 创建构造函数
            CodeConstructor constructor = new CodeConstructor();
            constructor.Attributes = MemberAttributes.Public;
            // 添加映射表
            constructor.Statements.Add(new CodeMethodInvokeExpression(
                new CodeBaseReferenceExpression(), "ToTable",
                new CodePrimitiveExpression("Cat_" + design.ModuleName)));
            //添加主键
            constructor.Statements.Add(new CodeMethodInvokeExpression(
                new CodeBaseReferenceExpression(), "HasKey",
                new CodeTypeReferenceExpression("i => i.Id")));
            //Ignore Id
            //constructor.Statements.Add(new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "Ignore", new CodeTypeReferenceExpression("i => i.Id")));
            exportClass.Members.Add(constructor);
            codeNamespace.Types.Add(exportClass);
            return codeNamespace;
        }
    }
}
